#include "pwm.h"

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#include <sys/time.h>
#include <signal.h>

static pwm_t *pwm;

/**
 * @brief 定时运行翻转LED
 * @param sig 
 * @author he (heweilong@huchuang.com)
 * @date 2025-08-04
 * @note
 */
void timeout_handler(int sig)
{
	double cycle = 0;
	if (pwm_get_duty_cycle(pwm, &cycle) < 0)
	{
		fprintf(stderr, "pwm_get_duty_cycle(): %s\n", pwm_errmsg(pwm));
		exit(1);
	}

	/*占空比每次增加1%*/
	cycle = (cycle + 0.01) > 1 ? 0 : cycle + 0.01;
	if (pwm_set_duty_cycle(pwm, cycle) < 0)
	{
		fprintf(stderr, "pwm_set_duty_cycle(): %s\n", pwm_errmsg(pwm));
		exit(1);
	}

	printf("pwm set cycle %.2f\r\n", cycle * 100);
}

/**
 * @brief 退出程序回调
 * @param sig 
 * @author he (heweilong@huchuang.com)
 * @date 2025-08-04
 * @note
 */
void ctrl_c_handle(int sig)
{
	printf("CTRL + C cb\r\n");

	struct itimerval disable = {0};
	setitimer(ITIMER_REAL, &disable, NULL);
	printf("Timer disabled\n");

	/*关闭pwm*/
	pwm_set_duty_cycle(pwm, 0);
	pwm_close(pwm);
	pwm_free(pwm);

	exit(0);
}


int main(void)
{
	printf("pwm demo\r\n");
	pwm = pwm_new();

	/* 打开pwm chip和readme中cat出来的chip保持一致 chanl选择0 */
	if (pwm_open(pwm, 3, 0) < 0) {
			fprintf(stderr, "pwm_open(): %s\n", pwm_errmsg(pwm));
			exit(1);
	}

	/* 1kHz */
	if (pwm_set_frequency(pwm, 1000) < 0) {
			fprintf(stderr, "pwm_set_frequency(): %s\n", pwm_errmsg(pwm));
			exit(1);
	}

	/* Set duty cycle to 0% */
	if (pwm_set_duty_cycle(pwm, 0) < 0) {
			fprintf(stderr, "pwm_set_duty_cycle(): %s\n", pwm_errmsg(pwm));
			exit(1);
	}

	/* Enable PWM */
	if (pwm_enable(pwm) < 0) {
			fprintf(stderr, "pwm_enable(): %s\n", pwm_errmsg(pwm));
			exit(1);
	}

	/*初始化定时器定时增大占空比*/
	signal(SIGALRM, timeout_handler);
	struct itimerval timer = {
		.it_value = {.tv_sec = 1, .tv_usec = 0},		// 首次触发 1秒
		.it_interval = {.tv_sec = 1, .tv_usec = 0}	// 触发周期 1秒
	};
	setitimer(ITIMER_REAL, &timer, NULL); // 启动定时器

	/*CTRL+C 回调*/
	signal(SIGINT, ctrl_c_handle);
	
	while (1)
	{
		sleep(1);
	}

	return 0;
}